package com.ruoyi.fun.controller;

import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.fun.domain.EcUserCouponNew;
import com.ruoyi.fun.service.IEcUserCouponNewService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 优惠券列表Controller
 * 
 * @author ruoyi
 * @date 2025-08-26
 */
@RestController
@RequestMapping("/fun/conponList")
public class EcUserCouponNewController extends BaseController
{
    @Autowired
    private IEcUserCouponNewService ecUserCouponNewService;

    /**
     * 查询优惠券列表列表
     */
    @PreAuthorize("@ss.hasPermi('fun:conponList:list')")
    @GetMapping("/list")
    public TableDataInfo list(EcUserCouponNew ecUserCouponNew)
    {
        startPage();
        Long orgId = getOrgId();
        // 103组织拥有不过滤的权限
        if (orgId != null && orgId == 103L) {
            orgId = null;
        }
        ecUserCouponNew.setOrgId(orgId);
        List<EcUserCouponNew> list = ecUserCouponNewService.selectEcUserCouponNewList(ecUserCouponNew);
        return getDataTable(list);
    }

    /**
     * 导出优惠券列表列表
     */
    @PreAuthorize("@ss.hasPermi('fun:conponList:export')")
    @Log(title = "优惠券列表", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, EcUserCouponNew ecUserCouponNew)
    {
        Long orgId = getOrgId();
        // 103组织拥有不过滤的权限
        if (orgId != null && orgId == 103L) {
            orgId = null;
        }
        ecUserCouponNew.setOrgId(orgId);
        List<EcUserCouponNew> list = ecUserCouponNewService.selectEcUserCouponNewList(ecUserCouponNew);
        ExcelUtil<EcUserCouponNew> util = new ExcelUtil<EcUserCouponNew>(EcUserCouponNew.class);
        util.exportExcel(response, list, "优惠券列表数据");
    }

    /**
     * 获取优惠券列表详细信息
     */
    @PreAuthorize("@ss.hasPermi('fun:conponList:query')")
    @GetMapping(value = "/{userCouponId}")
    public AjaxResult getInfo(@PathVariable("userCouponId") Long userCouponId)
    {
        return success(ecUserCouponNewService.selectEcUserCouponNewByCouponId(userCouponId));
    }

    /**
     * 新增优惠券列表
     */
    @PreAuthorize("@ss.hasPermi('fun:conponList:add')")
    @Log(title = "优惠券列表", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody EcUserCouponNew ecUserCouponNew)
    {
        try {
            ecUserCouponNew.setOrgId(getOrgId());
            return toAjax(ecUserCouponNewService.insertEcUserCouponNew(ecUserCouponNew));
        } catch (Exception e) {
            String errorMessage = e.getMessage();
            if (errorMessage != null) {
                if (errorMessage.contains("Duplicate entry") && errorMessage.contains("uk_coupon_code")) {
                    return error("优惠券代码已存在，请使用不同的优惠券代码");
                } else if (errorMessage.contains("foreign key constraint fails")) {
                    return error("数据关联错误，请检查相关数据是否存在");
                } else if (errorMessage.contains("cannot be null")) {
                    return error("必填字段不能为空，请检查表单数据");
                }
            }
            return error("新增优惠券失败：" + errorMessage);
        }
    }

    /**
     * 修改优惠券列表
     */
    @PreAuthorize("@ss.hasPermi('fun:conponList:edit')")
    @Log(title = "优惠券列表", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody EcUserCouponNew ecUserCouponNew)
    {
        return toAjax(ecUserCouponNewService.updateEcUserCouponNew(ecUserCouponNew));
    }

    /**
     * 删除优惠券列表
     */
    @PreAuthorize("@ss.hasPermi('fun:conponList:remove')")
    @Log(title = "优惠券列表", businessType = BusinessType.DELETE)
	@DeleteMapping("/{userCouponIds}")
    public AjaxResult remove(@PathVariable Long[] userCouponIds)
    {
        return toAjax(ecUserCouponNewService.deleteEcUserCouponNewByCouponIds(userCouponIds));
    }

    /**
     * APP端获取当前用户优惠券列表（无需权限验证）
     */
    @GetMapping("/app/list")
    public TableDataInfo getAppUserCouponList(EcUserCouponNew ecUserCouponNew)
    {
        startPage();
        // 直接根据用户ID和组织ID查询优惠券列表
        EcUserCouponNew query = new EcUserCouponNew();
        query.setCreateUserId(getUserId());
        query.setOrgId(getOrgId());
        List<EcUserCouponNew> list = ecUserCouponNewService.selectEcUserCouponNewList(query);
        return getDataTable(list);
    }

    /**
     * APP端获取优惠券详情（无需权限验证）
     */
    @GetMapping("/app/{couponId}")
    public AjaxResult getAppCouponInfo(@PathVariable("couponId") Long couponId)
    {
        EcUserCouponNew coupon = ecUserCouponNewService.selectEcUserCouponNewByCouponId(couponId);
        // 验证优惠券是否属于当前用户和组织
        if (coupon != null && coupon.getCreateUserId().equals(getUserId()) && coupon.getOrgId().equals(getOrgId())) {
            return success(coupon);
        }
        return error("优惠券不存在或无权限访问");
    }

    /**
     * APP端使用优惠券（无需权限验证）
     */
    @PostMapping("/app/use/{couponId}")
    public AjaxResult useAppCoupon(@PathVariable("couponId") Long couponId)
    {
        EcUserCouponNew coupon = ecUserCouponNewService.selectEcUserCouponNewByCouponId(couponId);
        // 验证优惠券是否属于当前用户和组织
        if (coupon == null || !coupon.getCreateUserId().equals(getUserId()) || !coupon.getOrgId().equals(getOrgId())) {
            return error("优惠券不存在或无权限访问");
        }
        
        // 检查优惠券状态
        if (!"0".equals(coupon.getUseStatus())) {
            return error("优惠券已使用或已过期");
        }
        
        // 更新优惠券状态为已使用
        coupon.setUseStatus("1");
        int result = ecUserCouponNewService.updateEcUserCouponNew(coupon);
        return toAjax(result);
    }

    /**
     * APP端获取可用优惠券数量（无需权限验证）
     */
    @GetMapping("/app/count")
    public AjaxResult getAppAvailableCouponCount()
    {
        EcUserCouponNew query = new EcUserCouponNew();
        query.setOrgId(getOrgId());
        query.setCreateUserId(getUserId());
        query.setUseStatus("0"); // 未使用状态
        List<EcUserCouponNew> list = ecUserCouponNewService.selectEcUserCouponNewList(query);
        return success(list.size());
    }
}